﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gasco.Business.Services;

public partial class Controls_product_index : System.Web.UI.UserControl
{
    private IProductService productService;

    public IProductService ProductService
    {
        get
        {
            if (productService == null)
                productService = new ProductService();

            return productService;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GetProducts(tbSearch.Text, 1, true, gvProducts.SortExpression, gvProducts.SortDirection.ToString());
            
        }
    }

    private void GetProducts(string keyword, int pageNumber, bool setPageCount ,string sortBy ,string desc)
    {
        ViewState["CurrentPage"] = pageNumber;

        if (setPageCount)
            gvProducts.VirtualItemCount = ProductService.CountSearchOrigins(keyword);

        gvProducts.DataSource = ProductService.SearchProducts(keyword, gvProducts.PageSize, pageNumber, sortBy, desc);
        gvProducts.DataBind();
    }

    protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvProducts.PageIndex = e.NewPageIndex;
        GetProducts(tbSearch.Text, e.NewPageIndex + 1, false, gvProducts.SortExpression, gvProducts.SortDirection.ToString());
    }

    protected void gvProducts_Deleting(object sender, GridViewDeleteEventArgs e)
    {
        ProductService service = new ProductService();
        service.DeleteProduct(Convert.ToInt32(gvProducts.DataKeys[e.RowIndex].Value));
        GetProducts(tbSearch.Text, 1, true, gvProducts.SortExpression, gvProducts.SortDirection.ToString());
    }

    protected void gvProduct_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["sort"] == null || ViewState["sort"].ToString() == "asc")
        {
            e.SortDirection = SortDirection.Descending;
            ViewState["sort"] = "desc";
        }
        else
        {
            e.SortDirection = SortDirection.Ascending;
            ViewState["sort"] = "asc";
        }
        GetProducts(tbSearch.Text, gvProducts.PageIndex + 1, false, e.SortExpression, e.SortDirection.ToString());
    }

    protected void lbSearch_Click(object sender, EventArgs e)
    {
        GetProducts(tbSearch.Text, 1, true, gvProducts.SortExpression, gvProducts.SortDirection.ToString());
    }
}
